import axios, {AxiosInstance, InternalAxiosRequestConfig, AxiosResponse} from 'axios'
import { message } from "antd";

const request: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 5000
})

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    config.headers[import.meta.env.VITE_MANAGE_TOKEN] = localStorage.getItem(import.meta.env.VITE_MANAGE_TOKEN) || ''
    return config
}, error => {
    return Promise.reject(error)
})

request.interceptors.response.use((response: AxiosResponse) => {
    const { data } = response
    if (!response.request.responseURL.includes('json')) {
        if (data.code === 501) {
            message.error(data.message)
            setTimeout(() => {
                window.location.href = '/#/login'
            }, 100)
            return
        }
    }
    return data
}, error => {
    return Promise.reject(error)
})

export default request